<template>
  <a-row class='content'>
    <a-col :xs='1' :sm='1' :md='2' :lg='2' :xl='2'></a-col>
    <a-col :style='{top:top}' :xs='24' :sm='11' :md='10' :lg='10' :xl='10'>
      <div id='tool_btn'>
        <a-row>
          <a-col align='center' :xs='24' :sm='24' :md='24' :lg='24' :xl='24'>
            <a-button type='primary' class='toolbox' v-for='(item,index) in jobManageList' :key='item.cupboardDoor'
                      shape='round'
                      @click='openTheDoor(item,index)'
                      :id='item.cupboardDoor'>
              {{ item.cabinetName }}
            </a-button>
          </a-col>
        </a-row>
      </div>
    </a-col>
    <a-col :style='{top:top}' :xs='24' :sm='4' :md='10' :lg='10' :xl='10'>
      <div id='job_btn'>
        <a-row>
          <a-col align='center' :xs='24' :sm='12' :md='12' :lg='12' :xl='12'>
            <!--虚假的更换工具，其实是偷偷初始化了-->
            <a-button class='job' @click='initTool' shape='round'>更换工具</a-button>
          </a-col>
          <a-col align='center' :xs='24' :sm='12' :md='12' :lg='12' :xl='12'>
            <a-button class='job' shape='round' @click='checkTheLine' :loading='checkLineLoading'>接线检测</a-button>
          </a-col>
        </a-row>
        <a-row>
          <a-col align='center' :xs='24' :sm='4' :md='12' :lg='12' :xl='12'>

            <a-button class='job' shape='round' @click='autoInspect' id='inspection' :loading='inspectionLoading'
                      :disabled='disabled'>自动检测
            </a-button>

          </a-col>

          <a-col align='center' :xs='24' :sm='4' :md='12' :lg='12' :xl='12'>
            <a-button class='job' shape='round' @click='inspection' id='jsjc' :disabled='endXJDisabled' :loading="endXJLoading">结束检测</a-button>
          </a-col>
        </a-row>
        <a-row>
          <a-col align='center' :xs='24' :sm='12' :md='12' :lg='12' :xl='12'>
            <a-button style='width: 80%;height:50px;margin: 10px' @click='logout()' shape='round'>退出系统</a-button>
          </a-col>
          <a-col align='center' :xs='24' :sm='4' :md='12' :lg='12' :xl='12'>
            <a-button class='job' shape='round' @click='openAllDoor' :loading='openAllDoorLoad' id='all'
                      :disabled='disabled'>一键开锁
            </a-button>
          </a-col>
        </a-row>
      </div>
    </a-col>

    <a-col :xs='1' :sm='1' :md='2' :lg='2' :xl='2'></a-col>

    <a-modal
      title='一键巡检'
      v-model='inspectionDialog'
      :confirm-loading='inspectionLoading'>
      <template slot='footer'>
        <a-row>
          <!--取消查看-->
          <a-button shape='round' @click='cancelInspect'>取消</a-button>
          <!--D1-->
          <a-button shape='round' @click="inspectionOk('D1')" type='primary'>箱子在位信息</a-button>
        </a-row>
        <a-row style='margin-top: 10px;margin-bottom: 10px'>
          <!--D2-->
          <a-button shape='round' @click="inspectionOk('D2')" type='primary'>手环在位信息</a-button>
          <!--D3-->
          <a-button shape='round' @click="inspectionOk('D3')" type='primary'>蓝牙配对信息</a-button>
          <!--D01-->
          <a-button shape='round' @click="inspectionOk('D01')" type='primary'>箱子设备状态信息</a-button>
          <!--D06-->
          <!--          <a-button shape="round" @click="inspectionOk('D06')" type="primary">箱子关箱记录信息</a-button>-->
        </a-row>
      </template>
      <a-row>
        <a-col :span='18'>
          <div style='display: inline'><h2 style='display: inline'>巡检结果：</h2></div>
        </a-col>
        <a-col :span='6'>
          <!--当D3返回信息存在未配对设备时，显示该按钮-->
          <a-button style='display: inline' :hidden='hide' type='primary' shape='round'
                    @click='matchBlueTooth' :loading='bluetoothLoading' :disabled='disabled'>
            蓝牙重新配对
          </a-button>
        </a-col>
      </a-row>
      <div v-html='datas'></div>
    </a-modal>
  </a-row>
</template>

<script>

import { postAction, putAction, getAction } from '@api/manage'
import { mapActions, mapGetters } from 'vuex'
import user from '../../store/modules/user'

export default {
  name: 'Toolbox',
  inject: ['reload'],
  data() {
    return {
      initToolLoading: false,
      initTitle: '',
      initDialog: false,
      initLoading: false,
      initDialogText: '等待初始化',

      disabled: false,
      disabledInspect: false,

      inspectionDialog: false,
      inspectionLoading: false,
      inspectionText: '',

      bluetoothLoading: false,
      Text: '',
      Text1: '',
      Text2: '',
      Text3: '',
      Text4: '',
      Text5: '',
      datas: '',
      hide: true,

      openAllDoorLoad: false,

      url: {
        status: '/jobmanage/jobManage/jobManageStatus',
        ctlist: '/cabinetmanage/cabinetManage/getCTList',
        openAllDoor: '/toolboxrest/unlock',
        inspection: '/toolboxrest/automaticInspection',
        bluetooth: '/toolboxrest/setBluetoothName',
        initToolboxInfo: '/toolboxrest/initToolboxInfo',
        endXJ: '/toolboxrest/closeAutomaticInspection',

        newAdd:'/newjobmanage/newjobManage/add',
        uploadData:'/jobmanage/jobManage/uploadData',
        judgeToolbox:"/newjobmanage/newjobManage/judgeToolbox",

      },
      jobManageList: [],
      timer: null,
      type: 0,
      equipmentNums: '',
      bluetoothNames: '',
      rightNavShow: true,
      top: '35%',
      endXJLoading:false,
      endXJDisabled:true,

      jobManage:{
        cupboardDoor: '',
        equipmentNum: '',
        status: '',
        toolboxName: '',
        cabinetName: '',
        operator: ''
      },
      index:'',

      checkLineLoading:false,
    }
  },
  created() {
    this.getCTList()
    this.isMobile()
    /*alert(localStorage.getItem("endXJDisabled"))*/
    let dis = localStorage.getItem("endXJDisabled")
    /*alert(dis)*/
    if(dis==="true"){
      this.endXJDisabled = true
    }
    if(dis==="false"){
      this.endXJDisabled = false
    }
  },
  mounted() {
    this.getLoginPerson()
  },
  methods: {
    ...mapActions(['Logout']),
    ...mapGetters(['userInfo']),
    openTheDoor(item,index){
      let _this = this
      this.jobManage = item
      this.index = index
      let params = {
        cupboardDoor:item.cupboardDoor,
        status:item.status
      }
      let text = document.getElementById(_this.jobManage.cupboardDoor).innerText
      document.getElementById(_this.jobManage.cupboardDoor).innerText = '开启中'
      postAction(this.url.newAdd,params).then(res=>{
        console.log(res)
        if (res.success) {
          /*_this.jobManage.operator = res.result.operator
          _this.jobManageList[_this.index].operator = res.result.operator
          _this.$set(_this.jobManageList[_this.index], 'status', '1')
          _this.jobManage.status = '1'*/

          _this.$message.success(_this.jobManage.cabinetName + '开锁成功！')

          _this.getStatus(_this.jobManage,this.index)
        } else {
          _this.$message.error(_this.cabinetName + '开锁失败,请重试')
          document.getElementById(_this.jobManage.cupboardDoor).innerText = text
        }
      }).catch(error=>{
        _this.$message.error("开锁失败！系统异常，请联系管理员！")
        document.getElementById(_this.jobManage.cupboardDoor).innerText = text
      })
    },
    //判断接线是否正常
    checkTheLine(){
      let _this = this
      if(this.jobManage.cupboardDoor==''){
        this.$message.warn("未选择任何工具柜")
      }else{
        let params = {
          cupboardDoor:this.jobManage.cupboardDoor
        }
        _this.checkLineLoading = true
        postAction(this.url.judgeToolbox,params).then(res=>{
          if(res==true){
            this.uploadData()
          }else{
            this.$message.error(this.jobManage.toolboxName+"接线有误，请重试")
          }
          _this.checkLineLoading = false
        }).catch(error=>{
          this.$message.error("工具箱接线有误！系统异常，请联系管理员！")
          _this.checkLineLoading = false
        })
      }
    },
    //数据上传远程接口
    uploadData(){
      let _this = this
      let parameter = {
        cupboardDoor: this.cupboardDoor,
        equipmentNum: this.equipmentNum
      }
      postAction(_this.url.uploadData,parameter).then(res=>{
        if(res.success){
          _this.getStatus(_this.jobManage,_this.index)
          _this.$message.success("数据上传成功！")
        }else{
          _this.$message.error("数据上传失败，请重试")
        }
      }).catch(error=>{
        _this.$message.error("数据上传失败！系统异常，请联系管理员！")
      })
    },
    getCTList() {
      let that = this
      getAction(this.url.ctlist).then(res => {
        let jobs = res.result
        for (let i = 0; i < jobs.length; i++) {
          that.jobManageList.push({
            cupboardDoor: jobs[i].cabinetCode,
            equipmentNum: jobs[i].toolboxNum,
            status: '3',
            toolboxName: jobs[i].toolboxName,
            cabinetName: jobs[i].cabinetName,
            operator: ''
          })
        }
        that.getJobManageStatus()
      })
    },
    getJobManageStatus() {
      let that = this
      for (let i = 0; i < that.jobManageList.length; i++) {
        let jobMangage = that.jobManageList[i]
        that.getStatus(jobMangage,i);
      }
    },
    getStatus(jobMangage,i){
      let that = this
      let params = {
        cupboardDoor: jobMangage.cupboardDoor,
        equipmentNum: jobMangage.equipmentNum
      }
      getAction(that.url.status, params).then(res => {
        if (res.result != null) {
          let job = res.result
          // that.jobManageList[i].operator = job.operator
          that.jobManageList[i].operator = job.operator
          if (job.status === '1') {
            that.jobManageList[i].status = '1'
            document.getElementById(job.cupboardDoor).style.backgroundColor = '#FF0000'
            document.getElementById(job.cupboardDoor).innerText = jobMangage.toolboxName + '作业中:' + job.operator
          } else if (job.status === '2') {
            that.jobManageList[i].status = '2'
            document.getElementById(job.cupboardDoor).style.backgroundColor = '#FF0000'
            document.getElementById(job.cupboardDoor).innerText = jobMangage.toolboxName + '更换工具中:' + job.operator
          } else {
            that.jobManageList[i].status = '3'
            document.getElementById(jobMangage.cupboardDoor).style.backgroundColor = '#00ff80'
            document.getElementById(jobMangage.cupboardDoor).innerText = jobMangage.cabinetName
          }
        }
      })
    },
    initTool() {
      /*alert(this.jobManage.cupboardDoor)*/
      if (this.jobManage.cupboardDoor == '') {
        this.$message.info('未选择任何工具柜')
      } else {
        this.initToolboxInfo()
      }
    },
    //初始化
    initToolboxInfo() {
      let _this = this
      _this.initToolLoading = true
      let parameter = {
        cupboardDoor: _this.jobManage.cupboardDoor
      }
      postAction(_this.url.initToolboxInfo, parameter).then(res => {
        if (res.success) {
          _this.$message.success(res.message)
          _this.initToolLoading = false
        } else {
          /*alert(111)*/
          _this.$message.error("初始化失败，请重试！")
          _this.initToolLoading = false
        }
      }).catch(error=>{
        _this.$message.error("初始化失败！系统异常，请联系管理员！")
        _this.initToolLoading = false
      })
    },
    //退出系统
    logout() {
      const that = this
      that.Logout({}).then(res => {
        that.$message.success('退出成功,2秒后将退回到首页')
        setTimeout(() => {
          that.$router.push({ path: '/' })
        }, 2000)
      }).catch(error => {
        that.$message.error({
          title: '错误',
          description: error.message
        })
      })
    },
    getLoginPerson() {
      /*console.log('用户角色：'+user.state.userRole)*/
      console.log(111+localStorage.getItem("role"))
      if (localStorage.getItem("role") !== 'admin'&&localStorage.getItem("role") !== 'super') {
        // document.getElementById('all').setAttribute('disabled', true)
        // document.getElementById('inspection').setAttribute('disabled', true)
        // document.getElementById('jsjc').setAttribute('disabled', true)
        document.getElementById('all').style.display = 'none'
        document.getElementById('inspection').style.display = 'none'
        document.getElementById('jsjc').style.display = 'none'
        /*document.getElementById('sdcsh').style.display = 'none'*/
      }
    },
    //一键开锁
    openAllDoor() {
      let _this = this
      let flag = 0
      let params = {
        cabinetCode: ''
      }
      this.jobManageList.forEach(item => {

        if (item.status == '3') {
          flag = 1
          params.cabinetCode = params.cabinetCode + item.cupboardDoor + ','
        }
      })
      if (flag == 0) {
        this.$message.info('当前所有柜门均为打开状态')
      } else {
        this.openAllDoorLoad = true
        postAction(this.url.openAllDoor, params).then(res => {
          if (res.success) {
            /*_this.disabled = true*/
            setTimeout(() => {
              _this.openAllDoorLoad = false
              this.$message.success(res.message)
              let arr = res.result.split(',')
              _this.operator = arr[arr.length - 1]
              /*alert(_this.operator)*/
              /*_this.jobManageList.forEach(job=>{
              document.getElementById(job.cupboardDoor).style.backgroundColor = '#FF0000'
              document.getElementById(job.cupboardDoor).innerText = job.toolboxName + '已借出:' + _this.operator
              })*/
            }, 1000)
            this.reload()
          } else {
            _this.openAllDoorLoad = false
            _this.$message.error('开锁失败')
          }
        })
      }
    },
    //开启自动检测
    autoInspect(){
      let _this = this
      _this.disabledInspect = false
      _this.inspectionLoading = true
      getAction(this.url.inspection).then(res => {
        console.log(res)
        if (res) {
          this.$message.success("自动检测开启成功！")
          _this.endXJDisabled = true
          setTimeout(()=>{
            localStorage.setItem("endXJDisabled",false)
            _this.endXJDisabled = false
          },10000)
        }else{
          this.$message.info('自动检测开启失败，请重试！')
        }
        _this.inspectionLoading = false
      })
    },
    //结束检测
    inspection() {
      this.endXJDisabled = false
      this.Text = ''
      this.endXJLoading = true
      getAction(this.url.endXJ).then(res => {
        if (res.D1 !== '' && res.D1 !== undefined) {
          this.Text1 = res.D1
        }
        if (res.D2 !== '' && res.D2 !== undefined) {
          this.Text2 = res.D2
        }
        if (res.D3 !== '' && res.D3 !== undefined) {
          this.Text3 = res.D3
        }
        if (res.D01 !== '' && res.D01 != undefined) {
          this.Text4 = res.D01
        }
        if (res.D06 !== '' && res.D06 !== undefined) {
          this.Text5 = res.D06
        }
        this.inspectionDialog = true
        this.$message.success('检测成功！')
        this.endXJLoading = false
      })

    },
    //巡检结果
    inspectionOk(type) {
      let that = this
      // console.log(typeof this.Text)
      // console.log(this.Text.split(',') + typeof this.Text.split(','))
      if (type == 'D1') {
        that.datas = that.datas + '<div><h3>箱子在位信息</h3></div>'
        if (this.Text1 == '') {
          that.datas = that.datas + '<div>暂无数据可查看</div><hr>'
        } else {
          that.datas = that.datas + '<div>' + this.Text1 + '</div><hr>'
        }
      } else if (type == 'D2') {
        that.datas = that.datas + '<div><h3>手环在位信息</h3></div>'
        if (this.Text2 == '') {
          that.datas = that.datas + '<div>暂无数据可查看</div><hr>'
        } else {
          that.datas = that.datas + '<div>' + this.Text2 + '</div><hr>'
        }
      } else if (type == 'D3') {
        that.datas = that.datas + '<div><h3>蓝牙配对信息</h3></div>'
        if (this.Text3 == '') {
          that.datas = that.datas + '<div>暂无数据可查看</div><hr>'
        } else {
          if (this.Text3 != '所有蓝牙连接处于正常状态') {
            setTimeout(() => {
              that.hide = false
            }, 1000)
            this.equipmentNums = this.Text3.split(';')[0].split('：')[1]
            this.bluetoothNames = this.Text3.split(';')[1].split('：')[1]
            that.datas = that.datas + '<div style="display: inline-block">' + this.Text3 + '</div>'
          } else {
            that.datas = that.datas + '<div>' + this.Text3 + '</div>'
          }
          that.datas = that.datas + '<hr>'
        }
      } else if (type == 'D01') {
        that.datas = that.datas + '<div><h3>箱子设备状态信息</h3></div>'
        if (this.Text4 == '') {
          that.datas = that.datas + '<div>暂无数据可查看</div><hr>'
        } else {
          let data = this.Text4.split(',')
          let num = 0
          this.timer = setInterval(() => {
            that.datas = that.datas + '<div>' + data[num] + '</div>'
            num++

            if (num == data.length) {
              that.datas = that.datas + '<hr>'
              clearInterval(that.timer)
            }
          }, 500)
        }
      }else {
        that.datas = that.datas + '<div>暂无数据可查看</div>'
      }
      that.disabledInspect = true
    },
    //取消查看巡检结果
    cancelInspect() {
      if (this.timer != null) {
        clearInterval(this.timer)
      }
      this.datas = ''
      this.inspectionDialog = false
      this.hide = true
    },
    //蓝牙配对
    matchBlueTooth() {
      let that = this
      this.bluetoothLoading = true
      let params = {
        equipmentNum: this.equipmentNums,
        bluetoothName: this.bluetoothNames
      }
      postAction(this.url.bluetooth, params).then(res => {
        if (res) {
          that.$message.success('配对成功')
        } else {
          that.$message.error('配对失败')
        }
      }).catch(error=>{
        that.$message.error("配对失败！系统异常，请联系管理员")
      })
      this.bluetoothLoading = false
    },
    // 添加判断方法
    isMobile() {
      this.deviceFlag = navigator.userAgent.match(
        /(phone|iPhone|ios|Android|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      )
      if (this.deviceFlag === null) {
        this.top = '35%'
        this.rightNavShow = true
      } else {
        this.rightNavShow = false
        this.top = '0'
      }
    },
  }
}
</script>

<style scoped lang='less'>
.content {
  width: 100%;
  height: 100%;
  background-image: url("../../assets/home.jpg");
  background-size: 100% 100%;
  background-position: top center;
}

.job {

  width: 80%;
  height: 60px;
  margin: 10px
}

.sdjob {
  color: #cc0000;
  width: 80%;
  height: 60px;
  margin: 10px
}

.toolbox {
  width: 45%;
  height: 80px;
  margin: 10px;

}
.toolbox:hover,.toolbox:focus {
  width: 45%;
  height: 80px;
  margin: 10px;
  background-color: #974cd5 !important;
}
#tool_btn .ant-btn {
  background-color: #00ff80;
  color: black;
  font-size: 25px;
}

#job_btn .ant-btn {
  font-size: 25px;
  background-color: #daf6ff;
}
.whetherfont {
  font-size: 20px;
}

</style>
